const axios = require('axios');

const BASE_URL = 'http://localhost:5000/api';

let authToken = '';
let userId = '';
let testTaskId = '';

async function testAISuggestionsComprehensive() {
  console.log('🧪 开始全面测试AI建议功能...\n');
  
  // Step 1: Login to get token
  console.log('🔐 正在登录获取认证token...');
  try {
    const loginResponse = await axios.post(`${BASE_URL}/auth/login/email`, {
      email: 'admin@aide.com',
      password: 'admin123456'
    });

    if (loginResponse.data.success) {
      authToken = loginResponse.data.token;
      userId = loginResponse.data.user.id;
      console.log('✅ 登录成功');
      console.log(`   用户ID: ${userId}`);
      console.log(`   Token: ${authToken.substring(0, 20)}...`);
    } else {
      console.log('❌ 登录失败:', loginResponse.data);
      return;
    }
  } catch (error) {
    console.log('❌ 登录错误:', error.response?.data || error.message);
    return;
  }

  // Step 2: Create a test task
  console.log('\n📝 创建测试任务...');
  try {
    const createTaskResponse = await axios.post(`${BASE_URL}/tasks`, {
      title: '测试AI建议功能的任务',
      description: '这是一个用于测试AI建议功能的任务',
      dueDate: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 明天
      priority: 'P2',
      category: 'work',
      tags: ['测试', 'AI建议']
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      }
    });

    if (createTaskResponse.data.id) {
      testTaskId = createTaskResponse.data.id;
      console.log('✅ 测试任务创建成功');
      console.log(`   任务ID: ${testTaskId}`);
    } else {
      console.log('❌ 创建测试任务失败:', createTaskResponse.data);
      return;
    }
  } catch (error) {
    console.log('❌ 创建测试任务错误:', error.response?.data || error.message);
    return;
  }

  // Step 3: Get AI suggestions
  console.log('\n🤖 获取AI建议...');
  try {
    const suggestionsResponse = await axios.post(`${BASE_URL}/ai/personalized-suggestions`, {
      context: `任务: 测试AI建议功能的任务`
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authToken}`
      }
    });

    if (suggestionsResponse.data.success && suggestionsResponse.data.suggestions) {
      console.log('✅ AI建议获取成功');
      console.log(`   建议数量: ${suggestionsResponse.data.suggestions.length}`);
      
      // 显示建议内容
      suggestionsResponse.data.suggestions.forEach((suggestion, index) => {
        console.log(`\n   建议 ${index + 1}:`);
        console.log(`   类型: ${suggestion.type}`);
        console.log(`   内容: ${suggestion.message}`);
        if (suggestion.actions && suggestion.actions.length > 0) {
          console.log(`   动作: ${suggestion.actions.map(a => a.label).join(', ')}`);
        }
      });
      
      // 测试建议动作
      await testSuggestionActions(suggestionsResponse.data.suggestions);
    } else {
      console.log('❌ 获取AI建议失败:', suggestionsResponse.data);
    }
  } catch (error) {
    console.log('❌ 获取AI建议错误:', error.response?.data || error.message);
  }

  // Step 4: Clean up test task
  console.log('\n🧹 清理测试任务...');
  try {
    const deleteResponse = await axios.delete(`${BASE_URL}/tasks/${testTaskId}`, {
      headers: {
        'Authorization': `Bearer ${authToken}`
      }
    });

    if (deleteResponse.data.message) {
      console.log('✅ 测试任务清理成功');
    } else {
      console.log('❌ 清理测试任务失败:', deleteResponse.data);
    }
  } catch (error) {
    console.log('❌ 清理测试任务错误:', error.response?.data || error.message);
  }

  console.log('\n🎉 全面测试完成！');
}

async function testSuggestionActions(suggestions) {
  console.log('\n📝 测试建议动作...');
  
  for (const suggestion of suggestions) {
    if (suggestion.actions && suggestion.actions.length > 0) {
      for (const action of suggestion.actions) {
        try {
          console.log(`\n   测试动作: ${action.label} (${action.action})`);
          
          const response = await axios.post(`${BASE_URL}/ai/suggestion-feedback`, {
            suggestionId: suggestion.id,
            action: action.action,
            rating: 5,
            feedbackText: `测试动作: ${action.label}`
          }, {
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${authToken}`
            }
          });

          if (response.data.success) {
            console.log(`   ✅ ${action.label} - 成功`);
          } else {
            console.log(`   ❌ ${action.label} - 失败: ${JSON.stringify(response.data)}`);
          }

        } catch (error) {
          console.log(`   ❌ ${action.label} - 错误: ${error.response?.data?.error || error.message}`);
        }
      }
    }
  }
}

// 运行测试
testAISuggestionsComprehensive().catch(console.error);
